// javaScript for jcvp_web
var ws;
var server_ip = window.location.host;
var g_chunks = [];
var g_chunks_id = 0;
var g_file;

function setupWebSocket()
{
	if ("WebSocket" in window) {
		ws = new WebSocket('ws://'+server_ip+'/ws/video');
		ws.onopen = function(event) {
			console.log('on opened!');
		};
		ws.onmessage = function(event) {
			if (typeof (event.data) === 'string') {
				json_data_parse(event.data);
			} else {
			}
		};
		ws.onclose = function(event) {
			console.log('on closed!');
		};
		ws.onerror = function(error) {
			console.error('on WebSocket error:', error);
		};
	} else {
		alert("unsupported WebSocket!");
	}
}

function json_data_parse(json_str)
{
	var json_obj = JSON.parse(json_str);
	if (json_obj.type === "cam_state") {
		if (undefined != root_obj.Width) {
			document.getElementById('js_image_width').textContent = json_obj.Width;
			if (document.getElementById('jc_image_width').value.trim() === '') {
				document.getElementById('jc_image_width').value = json_obj.Width;
			}
		}
		if (undefined != root_obj.Height) {
			document.getElementById('js_image_height').textContent = json_obj.Height;
			if (document.getElementById('jc_image_height').value.trim() === '') {
				document.getElementById('jc_image_height').value = json_obj.Height;
			}
		}
	} else {
		console.log('未知type:', json_obj.type);
	}
}

function on_jc_cam_init()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "cam_init",
			cam_uart: document.getElementById('jc_cam_uart').value,
			cam_name: document.getElementById('jc_cam_name').value,
			cam_baudrate: parseInt(document.getElementById('jc_cam_baudrate').value),
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);

		//frezz input
	}
}

function jc_image_size_set()
{
	if (ws.readyState === WebSocket.OPEN) {
		var json_obj = {
			type: "cam_ctrl",
			Width: parseInt(document.getElementById('jc_image_width').value),
			Height: parseInt(document.getElementById('jc_image_height').value),
		}
		var json_str = JSON.stringify(json_obj);
		ws.send(json_str);
	}
}

function on_page_load()
{
	setupWebSocket();
}
